const fs = window.require("fs");

export default function loadPageData(state, { that }) {
  let treeData = {};
  let treeData_string = "";
  let imgList = [];

  try {
    // 判断文件是否存在
    if (!fs.existsSync(that.__filePath + "/pageData.json")) {
      // 不存在则创造
      fs.mkdirSync(that.__filePath + "/developPageImage", { recursive: true });
      fs.writeFileSync(that.__filePath + "/pageData.json", "");
      return;
    }
    // 读取文件数据--页面数据
    treeData_string = fs
      .readFileSync(that.__filePath + "/pageData.json")
      .toString();
    // 读取图片数据，保存
    fs.readdirSync(that.__filePath + "/developPageImage").forEach((item) => {
      let path = that.__filePath + "/developPageImage/" + item;
      // 转换成blob
      let blob = URL.createObjectURL(new Blob([fs.readFileSync(path)]));

      // 判断有没有一样的图片
      if (treeData_string.includes(path)) {
        // 将页面数据中图片路径进行替换
        treeData_string = treeData_string.replace(path, blob);
        imgList.push({
          src: path,
          blob,
        });
      }
    });
    that.imgList = imgList;
  } catch (error) {
    console.error(error);
  }

  //判断有没有数据
  if (!treeData_string) return;
  // 数据格式化成对象
  treeData = JSON.parse(treeData_string);
  // 将不同页面数据更新
  // 这里不能直接赋值的，它是不能监听的--vue监听限制
  for (const key in treeData) {
    if (Object.hasOwnProperty.call(treeData, key)) {
      const element = treeData[key];
      that.$set(state.page.tree, key, element);
    }
  }
}
